package com.example.netty.netty.dubboRPC.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * @Author: 江涛
 * @CreateTime: 2022-09-22  21:22
 * @Description:
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    //保存ctx，给其他方法使用
    private ChannelHandlerContext context;
    private String result;
    private String param;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("成功建立通道");
        this.context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //接受结果
        result = msg.toString();
        System.out.println("接收到执行结果:"+result);
        //唤醒本线程，接收消息
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    /**
     * 以线程形式开启远程调用
     * @return
     * @throws Exception
     */
    @Override
    public synchronized Object call() throws Exception {
        context.writeAndFlush(param);
        System.out.println("发送参数:"+param);
        wait();
        System.out.println("唤醒线程，返回结果");
        //唤醒后直接返回结果
        return result;
    }

    public void setParam(String param) {
        this.param = param;
    }
}
